// subpkg/pages/sentence-practice/sentence-practice.js
Page({
  data: {
    currentIndex: 0,
    currentGroup: 0,
    isRecording: false,
    sentenceGroups: [
      {
        name: "第一组 - 日常问候",
        sentences: [
          {
            id: 1,
            text: "Good morning, teacher.",
            translation: "早上好，老师。",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=Good+morning+teacher&type=1"
          },
          {
            id: 2,
            text: "How are you today?",
            translation: "你今天好吗？",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=How are you today&type=1"
          },
          {
            id: 3,
            text: "Nice to meet you.",
            translation: "很高兴见到你。",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=Nice to meet you&type=1"
          },
          {
            id: 4,
            text: "See you tomorrow.",
            translation: "明天见。",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=See you tomorrow&type=1"
          },
          {
            id: 5,
            text: "Have a good day!",
            translation: "祝你今天愉快！",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=Have a good day&type=1"
          }
        ]
      },
      {
        name: "第二组 - 课堂用语",
        sentences: [
          {
            id: 1,
            text: "May I come in?",
            translation: "我可以进来吗？",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=May I come in&type=1"
          },
          {
            id: 2,
            text: "Please open your book.",
            translation: "请打开你的书。",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=Please open your book&type=1"
          },
          {
            id: 3,
            text: "I don't understand.",
            translation: "我不明白。",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=I don't understand&type=1"
          },
          {
            id: 4,
            text: "Can you repeat that?",
            translation: "你能再说一遍吗？",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=Can you repeat that&type=1"
          },
          {
            id: 5,
            text: "Thank you, teacher.",
            translation: "谢谢老师。",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=Thank you teacher&type=1"
          }
        ]
      },
      {
        name: "第三组 - 日常生活",
        sentences: [
          {
            id: 1,
            text: "What time do you get up?",
            translation: "你几点起床？",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=What time do you get up&type=1"
          },
          {
            id: 2,
            text: "I like playing football.",
            translation: "我喜欢踢足球。",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=I like playing football&type=1"
          },
          {
            id: 3,
            text: "What's your favorite food?",
            translation: "你最喜欢什么食物？",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=What's your favorite food&type=1"
          },
          {
            id: 4,
            text: "I go to school at 7:30.",
            translation: "我7:30去学校。",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=I go to school at seven thirty&type=1"
          },
          {
            id: 5,
            text: "Do you like swimming?",
            translation: "你喜欢游泳吗？",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=Do you like swimming&type=1"
          }
        ]
      },
      {
        name: "第四组 - 天气时间",
        sentences: [
          {
            id: 1,
            text: "What day is it today?",
            translation: "今天星期几？",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=What day is it today&type=1"
          },
          {
            id: 2,
            text: "It's sunny today.",
            translation: "今天是晴天。",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=It's sunny today&type=1"
          },
          {
            id: 3,
            text: "What's the weather like?",
            translation: "天气怎么样？",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=What's the weather like&type=1"
          },
          {
            id: 4,
            text: "What season is it?",
            translation: "现在是什么季节？",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=What season is it&type=1"
          },
          {
            id: 5,
            text: "It's time for lunch.",
            translation: "该吃午饭了。",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=It's time for lunch&type=1"
          }
        ]
      },
      {
        name: "第五组 - 家庭朋友",
        sentences: [
          {
            id: 1,
            text: "This is my family.",
            translation: "这是我的家人。",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=This is my family&type=1"
          },
          {
            id: 2,
            text: "How many people are there?",
            translation: "有多少人？",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=How many people are there&type=1"
          },
          {
            id: 3,
            text: "Who is your best friend?",
            translation: "谁是你最好的朋友？",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=Who is your best friend&type=1"
          },
          {
            id: 4,
            text: "I love my parents.",
            translation: "我爱我的父母。",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=I love my parents&type=1"
          },
          {
            id: 5,
            text: "Let's play together.",
            translation: "让我们一起玩吧。",
            audioUrl: "https://dict.youdao.com/dictvoice?audio=Let's play together&type=1"
          }
        ]
      }
    ],
    recorderManager: null,
    innerAudioContext: null,
    recordStatus: '准备录音',
    hasRecord: false,
    tempFilePath: '',
    dictType: 'course',
    grade3Expanded: false,
    grade4Expanded: false,
    starterExpanded: false,
    courseDict: {
      grade3: {
        name: '三年级',
        progress: 0,
        lessons: Array(8).fill().map((_, i) => ({
          id: i + 1,
          name: `第${i + 1}课`,
          completed: false
        }))
      },
      grade4: {
        name: '四年级',
        progress: 0,
        lessons: Array(8).fill().map((_, i) => ({
          id: i + 1,
          name: `第${i + 1}课`,
          completed: false
        }))
      }
    },
    cambridgeDict: {
      starter: {
        name: '预备级',
        progress: 0,
        semesters: {
          1: Array(16).fill().map((_, i) => ({
            id: i + 1,
            name: `第${i + 1}单元`,
            completed: false
          })),
          2: Array(16).fill().map((_, i) => ({
            id: i + 1,
            name: `第${i + 1}单元`,
            completed: false
          }))
        }
      }
    }
  },

  onLoad() {
    this.recorderManager = wx.getRecorderManager();
    this.innerAudioContext = wx.createInnerAudioContext();

    this.recorderManager.onStop((res) => {
      const { tempFilePath } = res;
      wx.hideLoading();
      this.evaluateRecording(tempFilePath);
    });

    this.recorderManager.onError((res) => {
      wx.hideLoading();
      wx.showToast({
        title: '录音失败',
        icon: 'error'
      });
      this.setData({ isRecording: false });
    });
  },

  playAudio() {
    const { sentenceGroups, currentGroup, currentIndex } = this.data;
    const currentSentence = sentenceGroups[currentGroup].sentences[currentIndex];
    this.innerAudioContext.src = currentSentence.audioUrl;
    this.innerAudioContext.play();
  },

  startRecording() {
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.record']) {
          this.beginRecording();
        } else {
          wx.authorize({
            scope: 'scope.record',
            success: () => {
              this.beginRecording();
            },
            fail: () => {
              wx.showModal({
                title: '需要录音权限',
                content: '请允许小程序使用录音功能，以便进行语音评测',
                success: (res) => {
                  if (res.confirm) {
                    wx.openSetting();
                  }
                }
              });
            }
          });
        }
      }
    });
  },

  beginRecording() {
    this.setData({ isRecording: true });
    this.recorderManager.start({
      duration: 60000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 48000,
      format: 'mp3'
    });

    this.recorderManager.onStart(() => {
      wx.showToast({
        title: '开始录音',
        icon: 'none'
      });
    });
  },

  stopRecording() {
    if (this.data.isRecording) {
      this.setData({ isRecording: false });
      this.recorderManager.stop();

      wx.showLoading({
        title: '评分中...',
      });
    }
  },

  evaluateRecording(audioFile) {
    const { sentenceGroups, currentGroup, currentIndex } = this.data;
    const currentSentence = sentenceGroups[currentGroup].sentences[currentIndex];

    // 创建音频上下文来分析录音
    const audioContext = wx.createInnerAudioContext();
    audioContext.src = audioFile;

    audioContext.onCanplay(() => {
      // 获取录音时长
      const duration = audioContext.duration;

      // 预期时长：每个单词大约需0.8秒
      const expectedDuration = currentSentence.text.split(' ').length * 0.8;

      // 计算时长得分（占40分）
      let durationScore = 40;
      if (duration < expectedDuration * 0.7) {
        durationScore = Math.floor(duration / expectedDuration * 40);
      } else if (duration > expectedDuration * 1.5) {
        durationScore = Math.floor((expectedDuration * 2 - duration) / expectedDuration * 40);
      }

      // 音量得分（占40分）- 这里简单给一个基础分
      const volumeScore = 35;

      // 完整度得分（占20分）
      const completenessScore = duration >= expectedDuration * 0.7 ? 20 : 10;

      // 总分
      const totalScore = durationScore + volumeScore + completenessScore;

      if (totalScore > 80) {
        wx.showModal({
          title: '太棒了！',
          content: `总分：${totalScore}\n` +
            `发音时长：${durationScore}\n` +
            `音量表现：${volumeScore}\n` +
            `完整度：${completenessScore}\n\n` +
            `录音时长：${duration.toFixed(1)}秒\n` +
            `预期时长：${expectedDuration.toFixed(1)}秒`,
          showCancel: false,
          success: () => {
            if (this.data.currentIndex < this.data.sentenceGroups[this.data.currentGroup].sentences.length - 1) {
              this.setData({
                currentIndex: this.data.currentIndex + 1
              });
            } else {
              getApp().addScore(100, 'sentence_practice');
              wx.showToast({
                title: '恭喜获得100积分！',
                icon: 'success',
                duration: 2000
              });
            }
          }
        });
      } else {
        let suggestions = [];
        if (duration < expectedDuration * 0.7) {
          suggestions.push('说得太快了，请放慢速度');
        } else if (duration > expectedDuration * 1.5) {
          suggestions.push('说得太慢了，请适当加快速度');
        }
        if (volumeScore < 30) {
          suggestions.push('声音可以再大一些');
        }
        if (completenessScore < 20) {
          suggestions.push('请完整读完整个句子');
        }

        wx.showModal({
          title: '继续加油！',
          content: `总分：${totalScore}\n` +
            `发音时长：${durationScore}\n` +
            `音量表现：${volumeScore}\n` +
            `完整度：${completenessScore}\n\n` +
            `录音时长：${duration.toFixed(1)}秒\n` +
            `预期时长：${expectedDuration.toFixed(1)}秒\n\n` +
            `建议：\n${suggestions.join('\n')}`,
          showCancel: false
        });
      }
    });

    audioContext.onError((res) => {
      console.error('音频播放错误：', res);
      wx.showToast({
        title: '评分失败，请重试',
        icon: 'none'
      });
    });

    // 开始播放以触发 onCanplay 事件
    audioContext.play();
  },

  switchGroup(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentGroup: index,
      currentIndex: 0  // 切换组别时重置句子索引
    });
  },

  prevSentence() {
    if (this.data.currentIndex > 0) {
      this.setData({
        currentIndex: this.data.currentIndex - 1
      });
    }
  },

  nextSentence() {
    const { currentGroup, currentIndex, sentenceGroups } = this.data;
    if (currentIndex < sentenceGroups[currentGroup].sentences.length - 1) {
      this.setData({
        currentIndex: currentIndex + 1
      });
    }
  },

  // 开始录音
  startRecord() {
    const recorderManager = wx.getRecorderManager()

    recorderManager.onStart(() => {
      this.setData({
        recordStatus: '正在录音...'
      })
    })

    // 监听录音错误
    recorderManager.onError((res) => {
      wx.showToast({
        title: '录音失败',
        icon: 'error'
      })
    })

    // 配置录音参数
    const options = {
      duration: 10000, // 最长录音时间，单位ms
      sampleRate: 16000, // 采样率
      numberOfChannels: 1, // 录音通道数
      encodeBitRate: 96000, // 编码码率
      format: 'mp3' // 音频格式
    }

    // 开始录音
    recorderManager.start(options)
  },

  // 停止录音
  stopRecord() {
    const recorderManager = wx.getRecorderManager()

    recorderManager.onStop((res) => {
      this.setData({
        tempFilePath: res.tempFilePath,
        hasRecord: true,
        recordStatus: '录音完成'
      })
    })

    recorderManager.stop()
  },

  // 播放录音
  playRecord() {
    const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.src = this.data.tempFilePath

    innerAudioContext.onPlay(() => {
      this.setData({
        recordStatus: '正在播放...'
      })
    })

    innerAudioContext.onEnded(() => {
      this.setData({
        recordStatus: '播放完成'
      })
    })

    innerAudioContext.play()
  },

  // 切换词库类型
  switchDictType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({ dictType: type });
  },

  // 切换年级/级别的展开状态
  toggleGrade(e) {
    const grade = e.currentTarget.dataset.grade;
    const expandKey = `${grade}Expanded`;
    this.setData({
      [expandKey]: !this.data[expandKey]
    });
  },

  // 选择课程
  selectLesson(e) {
    const { grade, lesson } = e.currentTarget.dataset;
    // 加载对应课程的句子数据
    this.loadLessonSentences(grade, lesson);
  },

  // 选择单元
  selectUnit(e) {
    const { level, semester, unit } = e.currentTarget.dataset;
    // 加载对应单元的句子数据
    this.loadUnitSentences(level, semester, unit);
  },

  // 加载课程词库的句子数据
  loadLessonSentences(grade, lesson) {
    wx.showLoading({
      title: '加载中...'
    });

    // 模拟加载数据
    setTimeout(() => {
      wx.hideLoading();
      // 这里应该是实际的数据加载逻辑
      this.setData({
        currentIndex: 0,
        // 加载新的句子数据
        sentenceGroups: []  // 这里需要设置实际的句子数据
      });
    }, 500);
  },

  // 加载剑桥词库的句子数据
  loadUnitSentences(level, semester, unit) {
    wx.showLoading({
      title: '加载中...'
    });

    // 模拟加载数据
    setTimeout(() => {
      wx.hideLoading();
      // 这里应该是实际的数据加载逻辑
      this.setData({
        currentIndex: 0,
        // 加载新的句子数据
        sentenceGroups: []  // 这里需要设置实际的句子数据
      });
    }, 500);
  }
});